from django.shortcuts import render,redirect,HttpResponse
from web.myform.project import ProjectModelForm
from django.http import JsonResponse
from web import models



def project_list(request):
	if request.method == 'GET':
		form = ProjectModelForm(request)
		# 重组数据结构
		project_dict = {'my':[],'join':[],'star':[]}

		my_project_list = models.Project.objects.filter(creator=request.tracer_obj.user_obj)
		for my_p in my_project_list:
			if my_p.star:
				project_dict['star'].append({'type':'my','value':my_p})
			else:
				project_dict['my'].append(my_p)

		join_project_list = models.ProjectUser.objects.filter(user=request.tracer_obj.user_obj)
		for join_p in join_project_list:
			if join_p.star:
				project_dict['star'].append({'type':'join','value':join_p.project})
			else:
				project_dict['join'].append(join_p.project)

		return render(request,'project_list.html',{'form':form,'project_dict':project_dict})
	else:

		form = ProjectModelForm(request,data=request.POST)
		if form.is_valid():

			# form.instance是保存前的model对象,可以给他添加数据
			form.instance.creator = request.tracer_obj.user_obj
			form.save()

			return JsonResponse({'status':True})

		else:
			return JsonResponse({'status':False,'error_msg':form.errors})

def project_star(request,type,pid):

	if type == 'my':
		models.Project.objects.filter(id=pid,creator=request.tracer_obj.user_obj).update(star=True)
		return redirect('project_list')

	else:
		models.ProjectUser.objects.filter(
			project_id=pid,
			user=request.tracer_obj.user_obj
		).update(star=True)
		return redirect('project_list')

def project_unstar(request,type,pid):
	if type == 'my':
		models.Project.objects.filter(id=pid,creator=request.tracer_obj.user_obj).update(star=False)
		return redirect('project_list')

	else:
		models.ProjectUser.objects.filter(
			project_id=pid,
			user=request.tracer_obj.user_obj
		).update(star=False)
		return redirect('project_list')
